from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from areas.models import Area
from areas.serializers import AreasSerializer, AddressSerializer
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from user.models import Address, User


# Create your views here.


class AreasView(CacheResponseMixin, ListAPIView):
    serializer_class = AreasSerializer
    queryset = Area.objects.filter(parent=None)


class AreaView(CacheResponseMixin, ListAPIView):
    serializer_class = AreasSerializer

    def get_queryset(self):

        pk = self.kwargs['pk']

        return Area.objects.filter(parent_id=pk)


class AddressView(CreateAPIView, ListAPIView):
    serializer_class = AddressSerializer
    queryset = Address.objects.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'addresses': serializer.data,
            'default_address_id': request.user.default_address_id,
            'limit': 6,
        })


class AddressesView(UpdateAPIView):

    serializer_class = AddressSerializer
    queryset = Address.objects.filter(is_deleted=False)

    def delete(self, request, pk):
        try:
            address = Address.objects.get(pk=pk)
        except:
            raise Response({'error':'用户查找失败'})

        address.is_deleted = True
        address.save()

        return Response({'message':'ok'})


class AddressStatusView(APIView):

    def put(self, request, pk):
        address = Address.objects.get(pk=pk)
        user = self.request.user
        user.default_address_id = address.id
        user.save()

        return Response({'message':'ok'}, status=200)


class TitleAddressView(APIView):

    def put(self, request, pk):

        address = Address.objects.get(pk=pk)

        address.title = request.data.get('title')

        address.save()

        return Response({'message':'OK'}, status=200)


